package com.hushan.elevator.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hushan.elevator.model.RiskRecord;
import com.hushan.elevator.model.RiskRecordElevStatus;
import com.hushan.elevator.service.DeviceInfoService;
import com.hushan.elevator.service.DeviceLogService;
import com.hushan.elevator.service.RiskRecordService;
import com.hushan.elevator.utils.*;
import com.hushan.elevator.vo.HttpDeviceEvent;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/d")
public class DeviceHttpPublish {
    final RiskRecordService riskRecordService;
    final DeviceLogService deviceLogService;

    @Value("${spring.minio.bucket.deviceImg}")
    private String deviceImg;
    @Value("${spring.minio.bucket.riskImg}")
    private String riskBucket;

    @Resource
    private MinioUtils minioUtils;

    final DeviceInfoService deviceInfoService;

    public DeviceHttpPublish(RiskRecordService riskRecordService, DeviceLogService deviceLogService, DeviceInfoService deviceInfoService) {
        this.riskRecordService = riskRecordService;
        this.deviceLogService = deviceLogService;
        this.deviceInfoService = deviceInfoService;
    }

    @Operation(summary = "设备发布事件的地址", description = "真实设备报警时间的接口")
    @PostMapping("/event")
    public Result captureInfo(@RequestBody String event) {

        HttpDeviceEvent deviceEvent = new HttpDeviceEvent();
        JSONObject jsonObject = JSONUtil.parseObj(event);
        BeanUtil.copyProperties(jsonObject, deviceEvent);
        EventTypeCategory category = EventTypeEnum.getCategory(deviceEvent.getEvent());
        if (category == EventTypeCategory.NORMAL) {
            deviceInfoService.online(deviceEvent.getDevid(),true);
            return Result.SUCCESS();
        }


        RiskRecord riskRecord = new RiskRecord();
        riskRecord.setDeviceSerial(deviceEvent.getDevid());
        riskRecord.setSerialNumber(String.valueOf(deviceEvent.getEvent()));
        riskRecord.setEventId(deviceEvent.getEventid());
        DateTime dateTime = new DateTime(deviceEvent.getTimestamp());
        riskRecord.setCreatedTime(dateTime.toLocalDateTime());
        riskRecord.setState(0);
        riskRecordService.addRiskRecord(riskRecord);


        RiskRecordElevStatus elevStatus = new RiskRecordElevStatus();
        elevStatus.setRecordId(riskRecord.getRecordId());
        BeanUtil.copyProperties(deviceEvent.elevstatus, elevStatus);
        BeanUtil.copyProperties(deviceEvent.acinfo, elevStatus);
        riskRecordService.addRiskRecordElevStatus(elevStatus);

        deviceLogService.onWarning(deviceEvent.getDevid(),deviceEvent.getEventid(),String.valueOf(deviceEvent.getEvent()),null);
        return new Result(ResultCode.SUCCESS);
    }

    @Operation(summary = "设备发布事件的地址",
            description = "图片上传")
    @PostMapping("/picture")
    public Result capturePicture(@RequestParam("file") MultipartFile[] files,
                                 @RequestParam("devid") String devid) throws IOException {

        for (MultipartFile file : files) {
            minioUtils.upload(file, devid + ".jpg", deviceImg);
            log.info("上传设备图片:{}", devid);
            try {
                String eventId = Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().lastIndexOf('.'));
                RiskRecord byEventId = riskRecordService.findByEventId(eventId);
                log.info("上传风险图片:{}", eventId);

                boolean isRisk = byEventId != null;
                if (isRisk) {
                    boolean existBucket = minioUtils.existBucket(riskBucket);
                    if (!existBucket)minioUtils.makeBucket(riskBucket);
                    String url = minioUtils.uploadReturnUrl(file, devid + '/' + file.getOriginalFilename(), riskBucket);
                    byEventId.setRiskPic(url);
                    riskRecordService.updateRiskRecord(byEventId);
                }
                deviceLogService.onCapture(devid,eventId);
            } catch (Exception e) {
                System.out.println(e);
                e.printStackTrace();
            }

        }

        return new Result(ResultCode.SUCCESS);
    }
}
